<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Business;
use addons\qingdongams\model\BusinessStatus;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\FormApproval;
use addons\qingdongams\model\Invoice;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\ExamineRecord as ExamineRecordModel;
use addons\qingdongams\model\Order;
use addons\qingdongams\model\PartsStock;
use addons\qingdongams\model\Workorder;
use addons\qingdongams\model\Quote;
use addons\qingdongams\model\Consume;
use addons\qingdongams\model\AchievementRecords;
use addons\qingdongams\model\PartsStockReload;
use addons\qingdongams\model\Contract;
use addons\qingdongams\model\Receivables;
use addons\qingdongams\model\Approval;
use addons\qingdongams\model\CustomerProduct;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\Achievement;
use addons\qingdongams\model\Leave;
use addons\qingdongams\model\AttendanceCard;
use think\Db;
use think\Exception;
use think\Log;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 审批记录
 */
class ExamineRecord extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //审批记录
    public function getList()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');

        $list = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => $relation_id,
        ])->with('checkStaff')->select();
        $list = collection($list)->toArray();


        $this->success('请求成功', $list);
    }

    //审核
    public function examine()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');
        $content = input('content', '');
        $status = input('status');
        $record = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => $relation_id,
            'status' => 0,
        ])->find();
        if (empty($record)) {
            $this->error('没有待审核数据');
        }
        $staff = Staff::info();
        Db::startTrans();
        try {
            $model = new ExamineRecordModel();
            if ($model->isUpdate(true)->save([
                    'status' => $status,
                    'content' => $content,
                    'check_time' => time(),
                    'remark' => ''
                ], ['id' => $record['id']]) == false) {
                throw new Exception('修改失败');
            }

            switch ($relation_type) {
                case $model::CONSUME_TYPE://费用
                    $rowModel = new Consume();
                    $row = $rowModel->where(['id' => $relation_id])->find();
                    break;
                case $model::CONTRACT_TYPE://订单
                    $rowModel = new Contract();
                    $row = $rowModel->where(['id' => $relation_id])->find();
                    break;
                case $model::RECEIVABLES_TYPE://回款
                    $rowModel = new Receivables();
                    $row = $rowModel->where(['id' => $relation_id])->find();
                    break;
                case $model::ACHIEVEMENT_TYPE://业绩目标
                    $rowModel = new AchievementRecords();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    break;
                case $model::APPROVAL_TYPE://工作审批
                    $rowModel = new Approval();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::PARTS_TYPE://零件
                    $rowModel = new PartsStockReload();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::QUOTE_TYPE://报价单
                    $rowModel = new Quote();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::WORKORDER_TYPE://工单
                    $rowModel = new Workorder();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::INVOICE_TYPE://发票
                    $rowModel = new Invoice();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::LEAVE_TYPE://请假
                    $rowModel = new Leave();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                case $model::CARD_TYPE://补卡
                    $rowModel = new AttendanceCard();
                    $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                    $row['staff_id'] = $row['create_staff_id'];
                    break;
                default:
                    throw new Exception('参数错误');
            }
            if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $record['id'], 'to_staff_id' => $this->auth->id])->find()) {
                Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
            }
            $check_staff_ids = explode(',', trim($row['check_staff_ids'], ','));
            $check_staff_ids[] = $staff->id;
            if ($status == 1) {//审核通过
                $flow = Flow::getstepdetail($relation_type, $relation_id);
                //给下一审核人发送通知
                $result = Flow::sendStepRecord($flow, $relation_type, $relation_id, $check_staff_ids, $staff->id);

                //已完成审核
                if ($result['status'] == true) {
                    $rowModel->save([
                        'check_status' => 2,
                        'check_staff_ids' => implode(',', $check_staff_ids),
                        'order_id' => $result['order_id']
                    ], ['id' => $relation_id]);
                    switch ($relation_type) {
                        case $model::CONTRACT_TYPE://订单
                            Customer::where(['id' => $row['customer_id']])->update(['contract_status' => 1]);
                            //订单签署成功后商机变为赢单
                            if ($row['business_id']) {
                                BusinessStatus::create(['business_id' => $row['business_id'], 'type' => 4, 'remark' => '订单签署']);
                                Business::where(['id' => $row['business_id']])->update(['contract_status' => 1, 'updatetime' => time()]);
                            }
                            $customerUpdate = ['contract_status' => 1, 'trade_date' => date('Y-m-d')];
                            $customerInfo = Customer::where(['id' => $row['customer_id']])->find();
                            if (!in_array($customerInfo['follow'], ['已经购买'])) {
                                $customerUpdate['follow'] = '准备付款';
                            }
                            Customer::where(['id' => $row['customer_id']])
                                ->update($customerUpdate);

                            $orderModel = new Order();
                            $order = [
                                'customer_id' => $row['customer_id'],
                                'contacts_id' => $row['contacts_id'],
                                'contract_id' => $row['id'],
                                'create_staff_id' => $row['owner_staff_id'],
                                'owner_staff_id' => $row['owner_staff_id'],
                            ];
                            $orderModel->isUpdate(false)->save($order);
                            $order_id = $orderModel->getLastInsID();

                            break;
                        case $model::ACHIEVEMENT_TYPE://业绩目标
                            $m = new Achievement();
                            $m->where(['type' => $row['type'], 'status' => $row['status'], 'obj_id' => $row['obj_id']])->delete();
                            unset($row['id']);
                            unset($row['createtime']);
                            unset($row['updatetime']);
                            unset($row['deletetime']);
                            $m->allowField(true)->save($row);
                            $row['staff_id'] = $row['obj_id'];
                            break;
                        /*case $model::ACHIEVEMENT_TYPE://业绩目标
                            $m = new Achievement();
                            $m->where([ 'type' => $row['type'], 'obj_id' => $row['obj_id']])->delete();
                            unset($row['id']);

                            $monthAchievement = round($row['yeartarget'] / 12, 2);
                            $row['january'] = $row['february'] = $row['march'] = $row['april'] = $row['may'] = $row['june']
                                = $row['july'] = $row['august'] = $row['september'] = $row['october']
                                = $row['november'] = $row['december'] = $monthAchievement;
                            $row['createtime']=strtotime($row['createtime']);
                            $m->allowField(true)->save($row);
                            $row['staff_id'] = $row['obj_id'];
                            break;*/
                        case $model::RECEIVABLES_TYPE://回款
                            $m = new Contract();
                            $contract = $m->where(['id' => $row['contract_id']])->with(['receivables'])->find();

                            if (!empty($contract['receivables']) && $contract['receivables']['repayment_money'] >= $contract['money']) {
                                Customer::where(['id' => $row['customer_id']])->update(['follow' => '已经购买']);
                                $m->save(['contract_status' => 1], ['id' => $row['contract_id']]);//已完成
                            }
                            break;
                        case $model::PARTS_TYPE://零件出入库

                            $parts = $row['parts'];
                            $add = [
                                'type' => $row['type'],
                                'odd_numbers' => $row['odd_numbers'],
                                'storage_time' => $row['storage_time'],
                                'desc' => $row['desc'],
                                'create_staff_id' => $row['create_staff_id'],
                            ];
                            foreach ($parts as $v) {
                                $add['parts_id'] = $v['id'];
                                $add['number'] = $v['number'];
                                PartsStock::addStock($add);
                            }
                            break;

                        case $model::WORKORDER_TYPE://工单
                            $update = [];
                            if ($row['is_charge'] == 2 || $row['money'] == 0) {
                                if ($row['workorder_type'] == '返厂维修') {
                                    $update['process'] = 5;
                                } else if (in_array($row['workorder_type'], ['上门维修', '配件安装', '电话售后'])) {
                                    $update['status'] = 3;
                                    Workorder::setComplete($row['id']);
                                }

                            } else {
                                $update['process'] = 4;
                            }
                            Workorder::where(['id' => $row['id']])->update($update);
                            Message::addMessage($relation_type, $relation_id, $row['owner_staff_id'], $staff->id,
                                "工单《{$row['workorder_number']}》费用审核成功,请及时查看！");
                            break;
                        case $model::QUOTE_TYPE:
                            Quote::where(['id' => $row['id']])->update([
                                'status' => 1]);
                            break;
                    }
                    Message::addMessage(Message::EXAMINE_ADOPT_TYPE, $record['id'], $row['owner_staff_id'] ?? $row['staff_id'], $staff->id);

                    //删除 或签的待审批通知
                    Message::setRead(Message::EXAMINE_TYPE, $record['id']);
                    ExamineRecordModel::where([
                        'relation_type' => $relation_type,
                        'relation_id' => $relation_id,
                        'status' => 0,
                    ])->update(['status' => 3, 'check_time' => time()]);
                } else {
                    $rowModel->save([
                        'check_staff_ids' => implode(',', $check_staff_ids),
                        'order_id' => $result['order_id']
                    ], ['id' => $relation_id]);
                }
            } else {
                //审核未通过
                $rowModel->save(['check_status' => 3, 'check_staff_ids' => ''], ['id' => $relation_id]);
                Message::addMessage(Message::EXAMINE_REFUSE_TYPE, $record['id'], $row['owner_staff_id'] ?? $row['staff_id'], $staff->id, '');
                //删除待审批通知
                $ids = ExamineRecordModel::where([
                    'relation_type' => $relation_type,
                    'relation_id' => $relation_id,
                    'status' => 0,
                ])->column('id');
                Message::where(['relation_type' => Message::EXAMINE_TYPE, 'relation_id' => ['in', $ids], 'status' => 0])->update(['read_time' => time(), 'status' => 1]);

                ExamineRecordModel::where([
                    'relation_type' => $relation_type,
                    'relation_id' => $relation_id,
                    'status' => 0,
                ])->update(['status' => 3, 'check_time' => time()]);
            }


            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('审核成功');
    }

    //批量审核费用
    public function examine_consume()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');
        $content = input('content');
        $status = input('status');

        $relation_id = explode(',', $relation_id);
        if (empty($relation_id)) {
            $this->error('参数错误');
        }
        $record = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => ['in', $relation_id],
            'status' => ['neq', 0],
        ])->select();
        if (!empty($record)) {
            $this->error('有已审核数据，请刷新页面');
        }
        $saveIds = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => ['in', $relation_id],
        ])->column('id');
        $staff = Staff::info();
        Db::startTrans();
        try {
            $model = new ExamineRecordModel();
            if ($model->isUpdate(true)->save([
                    'status' => $status,
                    'content' => $content,
                    'check_time' => time()
                ], ['id' => ['in', $saveIds]]) == false) {
                throw new Exception('修改失败');
            }

            switch ($relation_type) {
                case $model::CONSUME_TYPE://费用
                    $rowModel = new Consume();
                    $row = $rowModel->where(['id' => ['in', $relation_id]])->select();
                    $row = collection($row)->toArray();
                    break;
                default:
                    throw new Exception('参数错误');
            }
            if ($message_ids = Message::where(['relation_type' => 'examine', 'relation_id' => ['in', $saveIds], 'to_staff_id' => $this->auth->id])->column('id')) {
                Message::where(['id' => ['in', $message_ids]])->update(['status' => 1, 'read_time' => time()]);
            }
            foreach ($row as $r) {

                $rowModel = new Consume();
                $flow_staff_ids = explode(',', trim($r['flow_staff_ids'], ','));
                $check_staff_ids = explode(',', trim($r['check_staff_ids'], ','));
                $check_staff_ids[] = $staff->id;

                $diff = array_diff($flow_staff_ids, $check_staff_ids);
                if ($status == 1) {//审核通过
                    //记录
                    if (empty($diff)) {

                        $rowModel->save([
                            'check_status' => 2,
                            'check_staff_ids' => implode(',', $check_staff_ids)
                        ], ['id' => $r['id']]);
                        Message::addMessage($relation_type, $r['id'], $r['owner_staff_id'] ?? $r['staff_id'], $staff->id, '您提交的审批已审核通过！');
                    } else {
                        $diff = array_values($diff);
                        if ($relation_type == $model::CONSUME_TYPE) {
                            $rowModel->save(['check_staff_ids' => implode(',', $check_staff_ids), 'next_staff_id' => $diff[0], 'check_status' => 1], ['id' => $r['id']]);
                        } else {
                            $rowModel->save(['check_staff_ids' => implode(',', $check_staff_ids)], ['id' => $r['id']]);
                        }
                        $model::addExaminse($relation_type, $r['id'], $diff[0]);
                    }

                } else {

                    $rowModel->save(['check_status' => 3, 'check_staff_ids' => implode(',', $check_staff_ids)], ['id' => $r['id']]);
                    Message::addMessage($relation_type, $r['id'], $row['owner_staff_id'] ?? $row['staff_id'], $staff->id, '您提交的审批被拒绝！');
                }
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('审核成功');

    }

    //加签
    public function addExamineStaff()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');
        $staff_id = input('staff_id');
        $remark = input('remark/a');
        $model = new ExamineRecordModel();
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $rowModel = new Consume();
                break;
            case $model::CONTRACT_TYPE://订单
                $rowModel = new Contract();
                break;
            case $model::RECEIVABLES_TYPE://回款
                $rowModel = new Receivables();
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $rowModel = new AchievementRecords();
                break;
            case $model::PARTS_TYPE://零件
                $rowModel = new PartsStockReload();
                break;
            case $model::APPROVAL_TYPE://工作审批
                $rowModel = new Approval();
                break;
            case $model::QUOTE_TYPE://报价单
                $rowModel = new Quote();
                break;
            case $model::WORKORDER_TYPE://工单
                $rowModel = new Workorder();
                break;
            default:
                throw new Exception('参数错误');
        }
        $examine = ExamineRecordModel::where(['relation_type' => $relation_type, 'relation_id' => $relation_id, 'status' => 0])->find();
        ExamineRecordModel::where(['relation_type' => $relation_type, 'relation_id' => $relation_id, 'status' => 0])->update(['deletetime' => time()]);
        Message::setRead(Message::EXAMINE_TYPE, $examine['id']);

        $row = $rowModel->get($relation_id);
        if (empty($row)) {
            $this->error('信息不存在');
        }
        $row->save(['flow_staff_ids' => $staff_id]);
        $flow_staff_ids = explode(',', trim($staff_id, ','));
        $check_staff_ids = explode(',', trim(isset($row['check_staff_id']) ? $row['check_staff_id'] : $row['check_staff_ids'], ','));
        $diff = array_diff($flow_staff_ids, $check_staff_ids);
        $diff = array_values($diff);
        Message::setRead($relation_type, $relation_id);
        $model::addExaminse($relation_type, $relation_id, $diff[0]);

        $this->success('请求成功');
    }

    //审核人列表
    public function flowStaffList()
    {
        $relation_type = input('relation_type');
        $relation_id = input('relation_id');

        $model = new ExamineRecordModel();
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $rowModel = new Consume();
                break;
            case $model::CONTRACT_TYPE://订单
                $rowModel = new Contract();
                break;
            case $model::RECEIVABLES_TYPE://回款
                $rowModel = new Receivables();
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $rowModel = new AchievementRecords();
                break;
            case $model::PARTS_TYPE://零件
                $rowModel = new PartsStockReload();
                break;
            case $model::APPROVAL_TYPE://工作审批
                $rowModel = new Approval();
                break;
            case $model::QUOTE_TYPE://报价单
                $rowModel = new Quote();
                break;
            case $model::WORKORDER_TYPE://工单
                $rowModel = new Workorder();
                break;
            case $model::INVOICE_TYPE://发票
                $rowModel = new Invoice();
                break;
            default:
                throw new Exception('参数错误');
        }
        $row = $rowModel->get($relation_id);
        if (empty($row)) {
            $this->error('信息不存在');
        }
        $flow_staff_id = explode(',', $row->flow_staff_ids);
        $staff = Staff::where(['id' => ['in', $flow_staff_id]])->column('id,name,img,post', 'id');
        $data = [];
        foreach ($flow_staff_id as $id) {
            $data[] = $staff[$id] ?? [];
        }
        $this->success('请求成功', $data);
    }


    /**
     * 获取审批列表
     */
    public function get_examine_list()
    {
        $limit = input("limit/d", 10);
        //订单审批，回款审批、业绩目标审批、办公审批 费用
        $relation_type = input('type');
        $status = input('status', 0);
        if ($status == 1) {
            $status = array('in', '1,2');
        }
        $data = ExamineRecordModel::where(['relation_type' => $relation_type,
            'status' => $status,
            'check_staff_id' => $this->auth->id])->order('id desc')->paginate($limit)->toArray();
        if ($data['data']) {
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['content_info'] = Message::where(array('relation_id' => $v['id'],
                    'relation_type' => 'examine'))->value('content')?:$v['content'];
                if ($v['relation_type'] == ExamineRecordModel::CONSUME_TYPE) {
                    $data['data'][$k]['relation_name'] = Consume::where(['id' => $v['relation_id']])->value('consume_type');
                } elseif ($v['relation_type'] == ExamineRecordModel::CONTRACT_TYPE) {
                    $data['data'][$k]['relation_name'] = Contract::where(['id' => $v['relation_id']])->value('name');
                } elseif ($v['relation_type'] == ExamineRecordModel::RECEIVABLES_TYPE) {
                    $data['data'][$k]['relation_name'] = Receivables::where(['id' => $v['relation_id']])->value('number');
                } elseif ($v['relation_type'] == ExamineRecordModel::ACHIEVEMENT_TYPE) {
                    $data['data'][$k]['relation_name'] = AchievementRecords::where(['id' => $v['relation_id']])->value('year');;
                } elseif ($v['relation_type'] == ExamineRecordModel::APPROVAL_TYPE) {
                    $approval = Approval::where(['id' => $v['relation_id']])->value('formapproval_id');
                    $data['data'][$k]['relation_name'] = '';
                    if ($approval) {
                        $data['data'][$k]['relation_name'] = FormApproval::where(['id' => $approval])->value('name');
                    }

                } elseif ($v['relation_type'] == ExamineRecordModel::CARD_TYPE) {
                    $data['data'][$k]['relation_name'] = '补卡';
                } elseif ($v['relation_type'] == ExamineRecordModel::LEAVE_TYPE) {
                    $data['data'][$k]['relation_name'] = '请假';
                }elseif ($v['relation_type'] == ExamineRecordModel::INVOICE_TYPE) {
                    $data['data'][$k]['relation_name'] = Invoice::where(['id' => $v['relation_id']])->value('number');;
                } else {
                    $data['data'][$k]['relation_name'] = '';
                }
            }
        }


        $this->success('请求成功', $data);
    }
}
